{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\nHow to optimize convolution using TensorCores\n=============================================\n**Author**: `Siyuan Feng <https://github.com/Hzfengsy>`_\n\nIn this tutorial, we will demonstrate how to write a high performance convolution\nschedule using TensorCores in TVM. In this example, we assume the input to\nconvolution has a large batch. We strongly recommend covering the `opt-conv-gpu` tutorial first.\n\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "TensorCore Introduction\n-----------------------\nEach Tensor Core provides a 4x4x4 matrix processing array that operates\n:code:`D = A * B + C`, where A, B, C and D are 4x4 matrices as Figure shows.\nThe matrix multiplication inputs A and B are FP16 matrices, while the accumulation\nmatrices C and D may be FP16 or FP32 matrices.\n\nHowever, CUDA programmers can only use warp-level primitive\n:code:`wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag)` to perform\n16x16x16 half-precision matrix multiplication on tensor cores. Before invoking\nthe matrix multiplication, programmers must load data from memory into registers\nwith primitive :code:`wmma::load_matrix_sync`, explicitly. The NVCC compiler translates\nthat primitive into multiple memory load instructions. At run time, every thread loads\n16 elements from matrix A and 16 elements from B.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Preparation and Algorithm\n-------------------------\nWe use the fixed size for input tensors with 256 channels and 14 x 14 dimensions.\nThe batch size is 256. Convolution filters contain 512 filters of size 3 x 3.\nWe use stride size 1 and padding size 1 for the convolution. In the example, we use\nNHWCnc memory layout.The following code defines the convolution algorithm in TVM.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import tvm\nfrom tvm import te\nimport numpy as np\nfrom tvm.contrib import nvcc\n\n# The sizes of inputs and filters\nbatch_size = 256\nheight = 14\nwidth = 14\nin_channels = 256\nout_channels = 512\nkernel_h = 3\nkernel_w = 3\npad_h = 1\npad_w = 1\nstride_h = 1\nstride_w = 1\n\n# TensorCore shape\nblock_size = 16\n\nassert batch_size % block_size == 0\nassert in_channels % block_size == 0\nassert out_channels % block_size == 0\n\n# Input feature map: (N, H, W, IC, n, ic)\ndata_shape = (\n    batch_size // block_size,\n    height,\n    width,\n    in_channels // block_size,\n    block_size,\n    block_size,\n)\n# Kernel: (H, W, IC, OC, ic, oc)\nkernel_shape = (\n    kernel_h,\n    kernel_w,\n    in_channels // block_size,\n    out_channels // block_size,\n    block_size,\n    block_size,\n)\n# Output feature map: (N, H, W, OC, n, oc)\noutput_shape = (\n    batch_size // block_size,\n    height,\n    width,\n    out_channels // block_size,\n    block_size,\n    block_size,\n)\n\n# Reduction axes\nkh = te.reduce_axis((0, kernel_h), name=\"kh\")\nkw = te.reduce_axis((0, kernel_w), name=\"kw\")\nic = te.reduce_axis((0, in_channels // block_size), name=\"ic\")\nii = te.reduce_axis((0, block_size), name=\"ii\")\n\n# Algorithm\nA = te.placeholder(data_shape, name=\"A\", dtype=\"float16\")\nW = te.placeholder(kernel_shape, name=\"W\", dtype=\"float16\")\nApad = te.compute(\n    (\n        batch_size // block_size,\n        height + 2 * pad_h,\n        width + 2 * pad_w,\n        in_channels // block_size,\n        block_size,\n        block_size,\n    ),\n    lambda n, h, w, i, nn, ii: tvm.tir.if_then_else(\n        tvm.tir.all(h >= pad_h, h - pad_h < height, w >= pad_w, w - pad_w < width),\n        A[n, h - pad_h, w - pad_w, i, nn, ii],\n        tvm.tir.const(0.0, \"float16\"),\n    ),\n    name=\"Apad\",\n)\nConv = te.compute(\n    output_shape,\n    lambda n, h, w, o, nn, oo: te.sum(\n        Apad[n, h * stride_h + kh, w * stride_w + kw, ic, nn, ii].astype(\"float32\")\n        * W[kh, kw, ic, o, ii, oo].astype(\"float32\"),\n        axis=[ic, kh, kw, ii],\n    ),\n    name=\"Conv\",\n)\n\ns = te.create_schedule(Conv.op)\ns[Apad].compute_inline()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Memory Scope\n------------\nIn traditional GPU schedule, we have global, shared and local memory scope.\nTo support TensorCores, we add another three special memory scope: :code:`wmma.matrix_a`,\n:code:`wmma.matrix_b` and :code:`wmma.accumulator`. On hardware, all fragments scope\nstores at the on-chip registers level, the same place with local memory.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Designate the memory hierarchy\nAS = s.cache_read(Apad, \"shared\", [Conv])\nWS = s.cache_read(W, \"shared\", [Conv])\nAF = s.cache_read(AS, \"wmma.matrix_a\", [Conv])\nWF = s.cache_read(WS, \"wmma.matrix_b\", [Conv])\nConvF = s.cache_write(Conv, \"wmma.accumulator\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Define Tensor Intrinsic\n-----------------------\nIn fact, TensorCore is a special hardware operation. So, we can just use tensorize\nto replace a unit of computation with the TensorCore instruction. The first thing is\nthat we need to define tensor intrinsic.\n\nThere are four basic operation in TensorCore: :code:`fill_fragment`, :code:`load_matrix`,\n:code:`mma_sync` and :code:`store_matrix`. Since :code:`fill_fragment` and :code:`mma_sync`\nare both used in matrix multiplication, so we can just write following three intrinsics.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def intrin_wmma_load_matrix(scope):\n    n = 16\n    A = te.placeholder((n, n), name=\"A\", dtype=\"float16\")\n    BA = tvm.tir.decl_buffer(A.shape, A.dtype, scope=\"shared\", data_alignment=32, offset_factor=256)\n    C = te.compute((n, n), lambda i, j: A[i, j], name=\"C\")\n    BC = tvm.tir.decl_buffer(C.shape, C.dtype, scope=scope, data_alignment=32, offset_factor=256)\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n\n        BA = ins[0]\n        BC = outs[0]\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_load_matrix_sync\",\n                BC.data,\n                n,\n                n,\n                n,\n                BC.elem_offset // 256,\n                BA.access_ptr(\"r\"),\n                n,\n                \"row_major\",\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})\n\n\ndef intrin_wmma_gemm():\n    n = 16\n    A = te.placeholder((n, n), name=\"A\", dtype=\"float16\")\n    B = te.placeholder((n, n), name=\"B\", dtype=\"float16\")\n    k = te.reduce_axis((0, n), name=\"k\")\n    C = te.compute(\n        (n, n),\n        lambda ii, jj: te.sum(A[ii, k].astype(\"float\") * B[k, jj].astype(\"float\"), axis=k),\n        name=\"C\",\n    )\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, name=\"BA\", scope=\"wmma.matrix_a\", data_alignment=32, offset_factor=256\n    )\n    BB = tvm.tir.decl_buffer(\n        B.shape, B.dtype, name=\"BB\", scope=\"wmma.matrix_b\", data_alignment=32, offset_factor=256\n    )\n    BC = tvm.tir.decl_buffer(\n        C.shape, C.dtype, name=\"BC\", scope=\"wmma.accumulator\", data_alignment=32, offset_factor=256\n    )\n\n    def intrin_func(ins, outs):\n        BA, BB = ins\n        (BC,) = outs\n\n        def init():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\", \"tir.tvm_fill_fragment\", BC.data, n, n, n, BC.elem_offset // 256, 0.0\n                )\n            )\n            return ib.get()\n\n        def update():\n            ib = tvm.tir.ir_builder.create()\n            ib.emit(\n                tvm.tir.call_intrin(\n                    \"handle\",\n                    \"tir.tvm_mma_sync\",\n                    BC.data,\n                    BC.elem_offset // 256,\n                    BA.data,\n                    BA.elem_offset // 256,\n                    BB.data,\n                    BB.elem_offset // 256,\n                    BC.data,\n                    BC.elem_offset // 256,\n                )\n            )\n            return ib.get()\n\n        return update(), init(), update()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, B: BB, C: BC})\n\n\ndef intrin_wmma_store_matrix():\n    n = 16\n    A = te.placeholder((n, n), name=\"A\", dtype=\"float32\")\n    BA = tvm.tir.decl_buffer(\n        A.shape, A.dtype, scope=\"wmma.accumulator\", data_alignment=32, offset_factor=256\n    )\n    C = te.compute((n, n), lambda i, j: A[i, j], name=\"C\")\n    BC = tvm.tir.decl_buffer(C.shape, C.dtype, scope=\"global\", data_alignment=32, offset_factor=256)\n\n    def intrin_func(ins, outs):\n        ib = tvm.tir.ir_builder.create()\n        BA = ins[0]\n        BC = outs[0]\n        ib.emit(\n            tvm.tir.call_intrin(\n                \"handle\",\n                \"tir.tvm_store_matrix_sync\",\n                BA.data,\n                n,\n                n,\n                n,\n                BA.elem_offset // 256,\n                BC.access_ptr(\"w\"),\n                n,\n                \"row_major\",\n            )\n        )\n        return ib.get()\n\n    return te.decl_tensor_intrin(C.op, intrin_func, binds={A: BA, C: BC})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Scheduling the Computation\n--------------------------\nTo use TensorCores in TVM, we must schedule the computation into specific structure\nto match the tensor intrinsic. The same as traditional GPU programs, we can also use\nshared memory to boost the speed. If you have any questions about blocking and shared\nmemory, please refer `opt-conv-gpu`.\n\nIn this example, each block contains 2x4 warps, and each warp calls 4x2 TensorCore\ninstructions. Thus, the output shape of each warp is 64x32 and each block outputs\n128x128 titles. Due to the limit of shared memory space, we only load 2 blocks (2x128x128 tiles)\none time.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>*Warp-level Operation*\n\n  Note that all TensorCore instructions are warp-level instructions, which means all 32 threads\n  in a warp should do this instruction simultaneously. Making theadIdx.x extent=32 is one of the\n  easiest way to solve this. Then We can bind threadIdx.x to any loops except those contain\n  TensorCore intrinsics directly or indirectly. Also note that it is not the unique solution.\n  The only thing we should do is to make sure all threads in a warp can call TensorCore at the same time.</p></div>\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Define tiling sizes\nblock_row_warps = 4\nblock_col_warps = 2\nwarp_row_tiles = 2\nwarp_col_tiles = 4\nwarp_size = 32\nchunk = 2\n\nblock_x = te.thread_axis(\"blockIdx.x\")\nblock_y = te.thread_axis(\"blockIdx.y\")\nblock_z = te.thread_axis(\"blockIdx.z\")\nthread_x = te.thread_axis(\"threadIdx.x\")\nthread_y = te.thread_axis(\"threadIdx.y\")\nthread_z = te.thread_axis(\"threadIdx.z\")\n\nnc, hc, wc, oc, nnc, ooc = Conv.op.axis\nblock_k = s[Conv].fuse(hc, wc)\ns[Conv].bind(block_k, block_z)\nnc, nci = s[Conv].split(nc, factor=warp_row_tiles)\nblock_i, nc = s[Conv].split(nc, factor=block_row_warps)\noc, oci = s[Conv].split(oc, factor=warp_col_tiles)\nblock_j, oc = s[Conv].split(oc, factor=block_col_warps)\ns[Conv].reorder(block_k, block_i, block_j, nc, oc, nci, oci, nnc, ooc)\ns[Conv].bind(block_i, block_x)\ns[Conv].bind(block_j, block_y)\ns[Conv].bind(nc, thread_y)\ns[Conv].bind(oc, thread_z)\n\n# Schedule local computation\ns[ConvF].compute_at(s[Conv], oc)\nn, h, w, o, nnf, oof = ConvF.op.axis\nko, ki = s[ConvF].split(ic, factor=chunk)\ns[ConvF].reorder(ko, kh, ki, kw, n, o, nnf, oof, ii)\n\n# Move intermediate computation into each output compute tile\ns[AF].compute_at(s[ConvF], kw)\ns[WF].compute_at(s[ConvF], kw)\n\n# Schedule for A's share memory\ns[AS].compute_at(s[ConvF], kh)\nn, h, w, i, nn, ii = AS.op.axis\ntx, xo = s[AS].split(n, nparts=block_row_warps)\nty, yo = s[AS].split(xo, nparts=block_col_warps)\nt = s[AS].fuse(nn, ii)\nto, ti = s[AS].split(t, factor=warp_size)\ns[AS].bind(tx, thread_y)\ns[AS].bind(ty, thread_z)\ns[AS].bind(ti, thread_x)\n\n# Schedule for W's share memory\ns[WS].compute_at(s[ConvF], kh)\nkh, kw, ic, o, ii, oo = WS.op.axis\ntx, xo = s[WS].split(o, nparts=block_row_warps)\nty, yo = s[WS].split(xo, nparts=block_col_warps)\nt = s[WS].fuse(ii, oo)\nto, ti = s[WS].split(t, nparts=warp_size)\ns[WS].bind(tx, thread_y)\ns[WS].bind(ty, thread_z)\ns[WS].bind(to, thread_x)\ns[WS].vectorize(ti)\nprint(tvm.lower(s, [A, W, Conv], simple_mode=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Lowering Computation to Intrinsics\n----------------------------------\nThe last phase is to lower the computation loops down to TensorCore hardware intrinsics\nby mapping the 2D convolution to tensor intrinsics\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "s[AF].tensorize(AF.op.axis[-2], intrin_wmma_load_matrix(\"wmma.matrix_a\"))\ns[WF].tensorize(WF.op.axis[-2], intrin_wmma_load_matrix(\"wmma.matrix_b\"))\ns[Conv].tensorize(nnc, intrin_wmma_store_matrix())\ns[ConvF].tensorize(nnf, intrin_wmma_gemm())\nprint(tvm.lower(s, [A, W, Conv], simple_mode=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Generate CUDA Kernel\n--------------------\nFinally we use TVM to generate and compile the CUDA kernel, and evaluate the latency of convolution.\nSince TensorCores are only supported in NVIDIA GPU with Compute Capability 7.0 or higher, it may not\nbe able to run on our build server\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dev = tvm.cuda(0)\nif nvcc.have_tensorcore(dev.compute_version):\n    with tvm.transform.PassContext(config={\"tir.UnrollLoop\": {\"auto_max_step\": 16}}):\n        func = tvm.build(s, [A, W, Conv], \"cuda\")\n    a_np = np.random.uniform(size=data_shape).astype(A.dtype)\n    w_np = np.random.uniform(size=kernel_shape).astype(W.dtype)\n    a = tvm.nd.array(a_np, dev)\n    w = tvm.nd.array(w_np, dev)\n    c = tvm.nd.array(np.zeros(output_shape, dtype=Conv.dtype), dev)\n    evaluator = func.time_evaluator(func.entry_name, dev, number=10)\n    print(\"conv2d with tensor core: %f ms\" % (evaluator(a, w, c).mean * 1e3))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Summary\n-------\nThis tutorial demonstrates how TVM scheduling primitives can be used to\ncall TensorCores on specific GPUs.\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}